package com.obligatorio.domain.filtros;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.obligatorio.faces.utils.FacesUtils;
import com.obligatorio.login.Login;

public class AuthenticationFilter implements Filter {
	private static final Logger log = Logger
			.getLogger(AuthenticationFilter.class.getName());

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		log.info("doFilter()");

		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) req;
		Login objLogin = (Login) request.getSession().getAttribute("login");

		String reqURL = request.getRequestURL().toString();
		log.info("reqURL : " + reqURL);
		log.info(objLogin);

		// if (!reqURL.endsWith("ObligatorioJ2EE/")) {
		if (objLogin != null && !objLogin.usuarioLogueado()) {
			log.info(context.getExternalContext().getRequestPathInfo());
			log.info(context.getExternalContext().getRequestPathInfo()
					+ "login.xhtml");

			FacesUtils.setErrorMessage("Usted debe estar logueado al sistema.");
			((HttpServletResponse) resp).sendRedirect("../login.xhtml");
		} else {
			// TODO aca modificar para que siga con la peticion del usuario.
			if (!reqURL.contains("login.xhtml")) {
				log.info("La reqURL no contiene login.xhtml");
				chain.doFilter(req, resp);
			}
		}
		// } else {
		//
		// log.info("PASA");
		// ((HttpServletResponse) resp).sendRedirect("login.xhtml");
		// //chain.doFilter(req, resp);
		// }

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
